// 用户权限、路由控制
const auth = {
  /**
   * @description 设置菜单权限
   * @param list {Array} 菜单信息
   * @desc type 菜单类型（0：目录；1：菜单；2：按钮）
   * @desc isCheck 是否勾选（0：否；1：是）
   * @returns menus: 项目菜单，authList: 所有页面权限，filterMenus: 该用户当前的权限
   */
  setMenuList(list = []) {
    const menus = [];
    const authList = [];
    const filterMenus = [];
    const setFn = (arr, item, filterItem) => {
      Array.isArray(arr) && arr.forEach(value => {
        // permission  '0': 公司模块，'1'：项目菜单 '2'： 其它 '3': 项目模块
        const { children, type, isCheck, permission } = value;
        if (type === '1') authList.push(value);
        const hide = isCheck === '0';
        if (children && children.length) {
          const option = {
            ...value,
            hide: isCheck === '0',
            children: []
          };
          const filterOption = {
            ...value,
            hide: isCheck === '0',
            children: []
          };
          setFn(children, option.children, filterOption.children);
          if (!hide) {
            type !== '2' && permission === '1' && item.push(option);
            filterItem.push(filterOption);
          }
          return;
        }
        if (!hide) {
          const val = {
            ...value,
            hide: isCheck === '0',
          };
          type !== '2' && permission === '1' && item.push(val);
          filterItem.push(val);
        }
      });
    };
    setFn(list, menus, filterMenus);
    return {
      menus,
      filterMenus,
      authList
    };
  },
  /**
   * @description 过滤路由
   * @param data {Array} 路由信息
   * @param menus {Array} 接口返回的菜单
   */
  filterRoute(data, menus) {
    // 匹配菜单
    const findRoute = (targetPath, routes) => {
      if (!Array.isArray(routes)) return null;
      return routes.find(value => {
        const { children, path } = value;
        const hasIncludes = path === targetPath;
        if (targetPath === '/project/index' &&
          (hasIncludes || path === '/project')) return value;
        if (hasIncludes || targetPath === '/') return value;
        if (children && children.length) {
          return findRoute(targetPath, children);
        }
        return null;
      });
    };
    const setRouteFn = (list, newList = []) => {
      const result = newList;
      list.forEach(item => {
        const { children, path } = item;
        const route = findRoute(path, menus);
        const newRoute = {
          ...item,
          children: []
        };
        if (route) {
          result.push(newRoute);
          children && setRouteFn(children, newRoute.children);
        }
      });
      return result;
    };
    return setRouteFn(data);
  },
};

export default auth;
